﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace VelocityShop.Entities
{
    [Serializable()]
    public class Cart
    {
        private IList<CartItem> _items;

        public Cart()
        {
            _items = new List<CartItem>();
        }

        public void Add(CatalogItem item)
        { 
            //check whether exists same productId
            var query = from i in _items where i.ProductId == item.ProductId select i;

            if (query.Count() == 0)
            { 
                //add item to the cart
                _items.Add(new CartItem {ProductId =item.ProductId,
                                         Description =item.Description,
                                         Quantity = 1,
                                         UnitPrice = item.UnitPrice});
            }
            else
            {
                //increment cartItem quantity
                query.First().Quantity++;
            }


        }

        public void Remove(CartItem item)
        {
            //check whether exists same productId
            var query = from i in _items where i.ProductId == item.ProductId select i;

            if (query.Count() > 0)
            {
                //check cartItem quantity before removing or decrementing
                if (query.First().Quantity == 1)
                {
                    _items.Remove(item);
                }
                else
                {
                    //decrement cartItem quantity
                    query.First().Quantity--;
                }

            }
           
        }

        public void RemoveAt(int index)
        {
            _items.RemoveAt(index);
        }

        public ReadOnlyCollection<CartItem> Items
        {
            get { return new ReadOnlyCollection<CartItem>(_items); }
        }

        public decimal Total
        {
            get
            {
                var total = _items.Sum(item => item.Total);
                return total;
            }
        }

    }
}
